Skip to content

Latest commit

 

History

History
52 lines (41 loc) · 1.42 KB

File metadata and controls

52 lines (41 loc) · 1.42 KB

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:

What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7 

Solutions (Python)

1. Stack

# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) ->ListNode: stack1= [] stack2= [] whilel1: stack1.append(l1.val) l1=l1.nextwhilel2: stack2.append(l2.val) l2=l2.nexthead=Nonecarry=0whilestack1orstack2orcarry: digit=carrydigit+=stack1.pop() ifstack1else0digit+=stack2.pop() ifstack2else0carry=1ifdigit>9else0digit-=10ifdigit>9else0temp=ListNode(digit) temp.next=headhead=tempreturnhead
close